#pragma once
#include <iostream>
#include <memory>
#include <unistd.h>
#include "Socket.hpp"
using namespace LogMoudle;
using namespace SocketMoudle;
class SelectServer
{
    const static int defaultd = -1;
    const static int size = sizeof(fd_set) * 8;

public:
    SelectServer(uint16_t port)
        : _listensock(std::make_unique<TcpSocket>()), _isrunning(false)
    {
        _listensock->BuildTcpSocketMethod(port);
        for (int i = 0; i < size; i++)
        {
            _fd_arry[i] = defaultd;
        }
        _fd_arry[0] = _listensock->Fd();
    }
    void Start()
    {
        _isrunning = true;
        while (true)
        {
            fd_set rfds;    // 定义fds集合
            FD_ZERO(&rfds); // 清空fds
            int maxfd = defaultd;
            for (int i = 0; i < size; i++)
            {
                if (_fd_arry[i] == defaultd)
                {
                    continue;
                }
                FD_SET(_fd_arry[i], &rfds); // 将符合文件描述符的数设置到集合中
                if (maxfd < _fd_arry[i])
                {
                    maxfd = _fd_arry[i];
                }
            }
              PrintFd();
            int n = select(maxfd + 1, &rfds, nullptr, nullptr, nullptr); // 事件就绪检测
            switch (n)
            {
            case -1:
                LOG(loglevel::ERROR) << "select error";
                break;
            case 0:
                LOG(loglevel::DEBUG) << "time out...";
                break;
            default:
                // 有事件就绪,就不仅仅是新连接到来了吧？读事件就绪啊？
                LOG(loglevel::DEBUG) << "有事件就绪了..., n : " << n;
                Dispatcher(rfds); // 处理就绪的事件
                break;
            }
        }
        _isrunning = false;
    }
    void Dispatcher(fd_set &as)
    {
        for (int i = 0; i < size; i++)
        {
            if (_fd_arry[i] == defaultd)
                continue;
            // fd合法，不一定就绪
            if (FD_ISSET(_fd_arry[i], &as))
            {
                 if (_fd_arry[i] == _listensock->Fd())
                {
                    // listensockfd 新连接到来
                    Acceptr();
                }
                else
                {
                    // 普通的读事件就绪
                    Recver(_fd_arry[i], i);
                }
            }
        }
    }
    void Acceptr()
    {
        InetAddr client;
        int fd = _listensock->Accept(&client);
        if (fd >= 0)
        {
            LOG(loglevel::INFO) << "get a new link, sockfd: "
                                << fd << ", client is: " << client.StringAddr();
            int pos = 0;
            for (; pos < size; pos++)
            {
                if (_fd_arry[pos] == defaultd)
                {
                    break;
                }
            }
            if (pos == size)
            {
                // select装满了
                LOG(loglevel::WARNING) << "select server full";
                close(fd);
            }
            else
            {
                _fd_arry[pos] = fd;
            }
        }
    }
    void Recver(int fd, int pos) // 普通读取
    {
        char buffer[1024];
        ssize_t n = recv(fd, buffer, sizeof(buffer)-1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client say@ " << buffer << std::endl;
        }
        else if (n == 0)
        {
            LOG(loglevel::INFO) << "clien quit...";
            // 1. 不要让select在关系这个fd了
            close(fd);
            _fd_arry[pos] = defaultd;
        }
        else
        {
            LOG(loglevel::ERROR) << "recv error";
            // 1. 不要让select在关系这个fd了
            _fd_arry[pos] = defaultd;
            close(fd);
        }
    }
    void PrintFd()
    {
        std::cout << "_fd_array[]: ";
        for (int i = 0; i < size; i++)
        {
            if (_fd_arry[i] == defaultd)
                continue;
            std::cout << _fd_arry[i] << " ";
        }
        std::cout << "\r\n";
    }
    void Stop()
    {
        _isrunning = false;
    }
    ~SelectServer()
    {
    }

private:
    bool _isrunning;
    std::unique_ptr<Socket> _listensock;
    int _fd_arry[size];
};